
//
//  CZUserAccountViewModel.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {

	//单例 的全局访问点
	static let shareUserAccount: CZUserAccountViewModel = CZUserAccountViewModel()
	
	//获取归档对象
	override init() {
		super.init()
		userAccount = CZUserAcount.loadUserAccount()
		
	}
	
	var isLogin: Bool {
	
	return accessToken != nil
	}
	
	var accessToken: String? {
	
		guard let token = userAccount?.access_token else {
		return nil
		}
		
		let result = userAccount?.expiresDate?.compare(NSDate())
		if result == NSComparisonResult.OrderedDescending {
			
			return token
		} else {
		return nil
		}
	
	}
	
	
	//封装网络接收
	
	var userAccount: CZUserAcount?
	
	func requestAccessToken(code: String, complete: (isSuccess: Bool) -> ()) {
	
	
		CZNetWorkTools.sharedTools.requestAccessToken(code) {
		(response, error) -> () in
			if error != nil {
			complete(isSuccess: false)
				return
			
			}
			
			guard let dic = response as? [String: AnyObject] else {
			
				complete(isSuccess: false)
				return
			
			}
			
			let userAccount = CZUserAcount(dic: dic)
		
			self.requestUserInfo(userAccount, complete: complete)
		}
	
	
	}
	
	
	func requestUserInfo(userAccount: CZUserAcount, complete: (isSuccess: Bool) -> ()) {
	
		CZNetWorkTools.sharedTools.requestUserInfo(userAccount) {
		(response, error) ->() in
			
			if error != nil {
				print(error)
			complete(isSuccess: false)
				
				return
			
			}
		
			guard let dic = response as? [String: AnyObject] else {
			
			complete(isSuccess: false)
				
				return
			}
			
			userAccount.name = dic["name"] as? String
			userAccount.avatar_large = dic["avatar_large"] as? String
			
			self.userAccount = userAccount
			
			 let result = userAccount.saveUserAccount()
			
			if result {
			complete(isSuccess: true)
			
			} else {
			
			complete(isSuccess: false)
			}
			
		}
	
	
	}
	
	
	
}
















